package cn.pzhuweb.controller;

import cn.pzhuweb.pojo.Car;
import cn.pzhuweb.pojo.Message;
import cn.pzhuweb.service.CarService;
import cn.pzhuweb.service.imp.CarServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Servlet implementation class TodoServlet
 */
@WebServlet("/addcar")
public class AddCarServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String id_str = request.getParameter("id");
        String name = request.getParameter("name");
        String type = request.getParameter("type");
        String price_str = request.getParameter("price");
        // 3.数据类型转换
        int id;
        try {
            id = Integer.parseInt(id_str);
        } catch (Exception e) {
            response.getWriter().print("<script>alert('id不合法');window.location.href='insertcar.jsp'</script>");
            return;
        }
        double price;
        try {
            price = Double.parseDouble(price_str);
        } catch (Exception e) {
            response.getWriter().print("<script>alert('price不合法');window.location.href='insertcar.jsp'</script>");
            return;
        }
        Car car = new Car(id, name, type, price);
        CarService carService = new CarServiceImp();
        Message message = carService.addCarInfo(car);
        if (message.isSuccess()) {
            response.getWriter().print("<script>alert('" + message.getMsg() + "');window.location.href='success.jsp'</script>");
        } else {
            response.getWriter().print("<script>alert('" + message.getMsg() + "');window.location.href='insertcar.jsp'</script>");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws  IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
